package com.samphanie.auiu.biz_detail.biz.goods

import android.graphics.Color
import androidx.recyclerview.widget.RecyclerView
import com.samphanie.auiu.library.utils.AuiuDisplayUtil
import com.samphanie.auiu.library.utils.ColorUtil
import kotlin.math.abs
import kotlin.math.min

/**
 * @author ZSY
 */
class TitleScrollListener(thresholdDp: Float = 100f, val callback: (Int) -> Unit) :
    RecyclerView.OnScrollListener() {

    private val thresholdPx = AuiuDisplayUtil.dp2px(thresholdDp)
    private var lastFraction = 0f

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        // 判断列表的滑动距离 与thresholdPx 运算，计算当前滑动状态

        val viewHolder = recyclerView.findViewHolderForAdapterPosition(0) ?: return
        val top = abs(viewHolder.itemView.top).toFloat()

        // 计算当前滑动百分比
        val fraction = top / thresholdPx
        if (lastFraction > 1f) {
            lastFraction = fraction
            return
        }
        val newColor = ColorUtil.getCurrentColor(Color.TRANSPARENT, Color.WHITE, min(fraction, 1f))
        callback(newColor)
        lastFraction = fraction
    }
}